<template>
  <div class="table-page mt-10 pt-0 px-12">
    <div class="w-full flex-1 overflow-hidden">
      <a-table
        row-key="id"
        v-model:columns="columns"
        :loading="loading"
        :data="tableData"
        :selected-keys="checkedValue"
        :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
        :pagination="pagination"
        :row-selection="{ type: 'radio' }"
        @select="onSelect"
      >
        <template #isTop="{ record }">
          <a-switch :checked-value="1" :unchecked-value="0" v-model="record.isTop" disabled></a-switch>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script setup>
import ImgHoverPreview from '@/components/ImgHoverPreview/index.vue'
import { businessSchoolCateList, linkSelect } from '@/apis'
import { usePagination } from '@/hooks'
const props = defineProps(['tabCurrentInfo', 'displayInfo'])
const emit = defineEmits(['handleCheck'])
const columns = ref([
  {
    title: '分类名称',
    width: 120,
    dataIndex: 'name'
  },
  {
    title: '分类图片',
    width: 120,
    render: (data) => {
      const url = data.record.pic
      return h(ImgHoverPreview, { url, width: 50 })
    }
  },
  {
    title: '布局样式',
    width: 120,
    render: (data) => {
      const styleType = data.record.styleType
      return styleType == 1 ? '横版平铺' : '竖版平铺'
    }
  }
])

const loading = ref(false)
const tableData = ref([])
const checkedValue = ref([])
const listParams = reactive({
  pageSize: 10,
  page: 1
})
const { pagination, setTotal } = usePagination(() => getTableData(), { defaultPageSize: listParams.pageSize })
// 获取列表数据
const getTableData = async () => {
  try {
    loading.value = true
    const res = await businessSchoolCateList(listParams)
    tableData.value = res.data.list.map((item) => {
      return { ...item, children: undefined }
    })
    setTotal(res.data?.count ?? 0)
  } finally {
    loading.value = false
  }
}
getTableData()

// 表格页码改变
const changeCurrent = (e) => {
  pagination.current = listParams.page = e
  getTableData()
}

watch(
  () => props.displayInfo,
  (newValue) => {
    if (newValue.typeId == 23 && newValue.id) {
      checkedValue.value = [Number(newValue.id)]
      listParams.id = newValue.id
    } else {
      checkedValue.value = []
    }
    changeCurrent(1)
  },
  { deep: true, immediate: true }
)

// 选择
const onSelect = async (e) => {
  const itemData = tableData.value.find((item) => {
    return e[0] === item.id
  })
  const res = await linkSelect({
    rule: props.tabCurrentInfo.rule,
    isLogin: props.tabCurrentInfo?.isLogin ?? undefined,
    param: {
      categoryId: itemData.id,
      title: itemData.name
    }
  })
  emit('handleCheck', res.data ?? '')
}
</script>

<style lang="scss" scoped></style>
